package com.pn.service.impl;

import com.pn.entity.Result;
import com.pn.entity.User;
import com.pn.mapper.UserMapper;
import com.pn.page.Page;
import com.pn.service.UserService;
import com.pn.utils.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    /**
     * @param userCode
     * @return
     */
    @Override
    public User queryUserByCode(String userCode) {
        return userMapper.findUserByCode(userCode);
    }

    /**
     * @param page
     * @param user
     * @return
     */
    @Override
    public Page queryUserByPage(Page page, User user) {

        Integer userCount = userMapper.findUserCount(user);
        System.out.println(userCount);
        List<User> userList = userMapper.findUserPage(page, user);

        page.setTotalNum(userCount);
        page.setResultList(userList);

        return page;
    }

    /**
     * @param user
     * @return
     */
    @Override
    public Result saveUser(User user) {
        User u = userMapper.findUserByCode(user.getUserCode());
        if(u != null){
            return Result.err(Result.CODE_ERR_BUSINESS, "账号已经存在");
        }
        String pwd = DigestUtil.hmacSign(user.getUserPwd());
        user.setUserPwd(pwd);
        int i = userMapper.insertUser(user);
        if(i > 0){
           return Result.ok("添加成功");
        }

        return Result.err(Result.CODE_ERR_BUSINESS, "用户添加失败");
    }

    /**
     * @param user
     * @return
     */
    @Override
    public Result setUserState(User user) {
        int i = userMapper.setStateByUid(user.getUserId(), user.getUserState());
        if(i > 0){
            return Result.ok("启用或禁用用户成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "启用或禁用用户失败");
    }

    //根据用户id删除用户的业务方法
    @Override
    public int deleteUserById(Integer userId) {
        //根据用户id修改用户状态为删除状态
        return userMapper.setUserDelete(userId);
    }

    //修改用户昵称的业务方法
    @Override
    public Result updateUserName(User user) {
        //根据用户id修改用户昵称
        int i = userMapper.updateNameById(user);
        if(i>0){//修改成功
            return Result.ok("用户修改成功！");
        }
        //修改失败
        return Result.err(Result.CODE_ERR_BUSINESS, "用户修改失败！");
    }

    //重置密码的业务方法
    @Override
    public Result resetPwd(Integer userId) {

        //创建User对象并保存用户id和加密后的重置密码123456
        User user = new User();
        user.setUserId(userId);
        user.setUserPwd(DigestUtil.hmacSign("123456"));

        //根据用户id修改密码
        int i = userMapper.updatePwdById(user);

        if(i>0){//密码修改成功
            return Result.ok("密码重置成功！");
        }
        //密码修改失败
        return Result.err(Result.CODE_ERR_BUSINESS, "密码重置失败！");
    }
}
